import json
import random, re
import time,requests

import redis
from django.http import HttpResponse

from flask import Blueprint, jsonify, request, make_response, redirect
from flask_restful import reqparse, Api

from utils.MySms import SmsTool
from utils.myredis import r
from utils.db import db
from utils.MyJwt import JwtTool
from utils.captcha.captcha import captcha
from models.model import Sflogin,User

user_bp = Blueprint('user_bp', __name__, url_prefix='/user')
api = Api(user_bp)

## 看过了
# #钩子函数
# @user_bp.before_request
# def gz():
#     # 获取token
#     req = reqparse.RequestParser()
#     req.add_argument('token', default='', location='headers')
#     args = req.parse_args()
#     token = args['token']
#
#     # 解析token
#     payload = Jwt_Token().valid(token)
#     print(payload)
#     if not payload:
#         uid = 0
#     else:
#         if payload == -1:
#             uid = -1
#         else:
#             uid = payload['user_id']
#
#     g.uid = uid
#     g.jwt_token = token
#
# # 强制登录的装饰器
# def login(func):
#     def warpper(*args, **kwargs):
#         # 在这里写装饰器的内容
#         if not g.uid:
#             return jsonify({
#                 'code': 403,
#                 'msg': '用户未登录'
#             })
#         if g.uid == -1:
#             return jsonify({
#                 'code': 666,
#                 'msg': 'Token已过期'
#             })
#
#         key = 'token_%s' % g.jwt_token
#         rds = SmsSdk().rds
#         is_exists = rds.exists(key)
#         if is_exists:
#             return jsonify({
#                 'code':403,
#                 'msg':'token失效'
#             })
#         return func(*args, **kwargs)
#     return warpper

#  # 发送验证码
# @user_bp.route("/sendcode", methods=["POST"])
# def sendcode():
#     # 获取手机号
#     req = reqparse.RequestParser()
#     req.add_argument('mobile')
#     args = req.parse_args()
#
#     if not args["mobile"]:
#         return jsonify({
#             'code': 204,
#             'msg': '信息不完整',
#         })
#
#     code = str(random.randint(100000, 999999))
#     rs = redis.Redis(host='127.0.0.1', port=6379, password="123")
#     key = 'sms_%s' % args["mobile"]
#     rs.set(key, code)
#     datas = (code, 5)
#     resp = SmsSDK(appId, accId, auth_token).sendMessage('1', args["mobile"], datas)
#     resp = json.loads(resp)
#     if resp['statusCode'] == '000000':
#         return jsonify({
#             'code': 400,
#             'msg': '发送失败',
#             '验证码': code
#         })
#     else:
#         return jsonify({
#             'code': 200,
#             'msg': '发送成功'
#         })
#
#
# # 图片验证码
# @user_bp.route('/imagecode')
# def imagecode():
#     uuid = request.args.get('uuid')
#     name, text, image = captcha.generate_captcha()
#     res = make_response(image)
#     res.headers['Content-Type'] = 'image/jpg'
#     # 存入redis
#     MyRedis().set_str(uuid, text)
#     return res
#
#
# # 登陆
# @user_bp.route('/login', methods=["POST"])
# def login():
#     req = reqparse.RequestParser()
#     req.add_argument('mobile', required=True)
#     req.add_argument('code', required=True)
#     args = req.parse_args()
#
#     if not args['mobile'] and args['code']:
#         return jsonify({
#             "code": 400,
#             "msg": '参数填写完整'
#         })
#     key = 'sms_%s' % args['mobile']
#     rs = MyRedis().get_str(key)
#     if not rs:
#         return jsonify({
#             "code": 400,
#             "msg": '验证码过期'
#         })
#     if rs != args['code']:
#         return jsonify({
#             "code": 400,
#             "msg": '验证码错误'
#         })
#     sql = "select * from views where mobile=%s" % args['mobile']
#
#     rs = DB.find(sql)
#
#     # 没有用户
#     if not rs:
#         sql = "insert into views(name,mobile) values(%s,%s)" % (args['mobile'], args['mobile'])
#         DB.update(sql)
#         DB.commit()
#
#     sql = "select * from views where mobile=%s" % args['mobile']
#     rs = DB.find(sql)
#
#     print(type(rs),rs, "?????????????????????????????????????????/")
#
#     payload = {'data': {
#         "id": rs['id'],
#         'name': rs['mobile'],
#         "exp": int(time.time()) + 3600
#     }}
#
#     token = MyJwt().jwt_encode(payload)
#     return jsonify({
#         "code": 200,
#         "msg": '登录成功',
#         "data": {
#             'token': token,
#             "id": rs['id'],
#             "name": rs['name']
#         }
#     })



# 发送验证码
@user_bp.route('/smscole',methods=["POST"])
def smscole():
    req = reqparse.RequestParser()
    req.add_argument("mobile", required=True)
    args = req.parse_args()

    # 判断手机号是否为空
    if not args['mobile']:
        return jsonify({
            "code": 400,
            "msg": "手机号不能为空"
        })

    # 判断手机号是否正确
    rule = r'^1[3-9][0-9]{9}$'
    rs = re.findall(rule,args["mobile"])
    if not rs:
        return jsonify({
            "code": 400,
            "msg": "手机号格式错误"
        })
    code = random.randint(1000, 9999)
    print(code, "111111111")

    s = SmsTool().send(args['mobile'], code)
    print(s)

    if s:
        return jsonify({
            'code': 200,
            'msg': '发送成功'
        })
    else:
        return jsonify({
            'code': 400,
            'msg': '发送失败',
            "ss": code
        })



# 图片验证码
@user_bp.route('/imagecode')
def imagecode():
    uuid = request.args.get('uuid')
    name, text, img = captcha.generate_captcha()
    res = make_response(img)
    res.headers['Content-Type'] = 'image/jpg'

    # 添加redis
    key = "uuid_" + uuid
    r.set_str(key, text, 300)
    return res



# 登录
@user_bp.route('/login', methods=['POST'])
def login():
    req = reqparse.RequestParser()
    req.add_argument("mobile", required=True)
    req.add_argument("uuid", required=True)
    req.add_argument("uuid_code", required=True)
    req.add_argument("code", required=True)
    args = req.parse_args()

    # 判断手机号是否为空
    if not all([args['mobile'], args['uuid'], args['code']]) :
        return jsonify({
            "code": 400,
            "msg": "数据不能为空"
        })

    # 连接redis判断图片验证码
    key = 'uuid_' + args['uuid']
    code_image = r.get_str(key)
    if not code_image or code_image != args['uuid_code']:
        return jsonify({
            "code": 400,
            "msg": "图片验证码不存在或过期"
        })

    # 连接redis判断容联云发送验证码
    key = 'sms_' + args['mobile']
    code_byte = r.get_str(key)
    # 判断验证码是否过期
    if not code_byte:
        return jsonify({
            "code": 400,
            "msg": "验证码过期"
        })

    # 判断验证码是否错误
    if args['code']!=code_byte:
        return jsonify({
            "code": 400,
            "msg": "验证码错误"
        })

    sql = "select * from user where mobile=%s" %args['mobile']
    user_info = db.find(sql)

    # 判断有没有这个手机号否则注册
    if not user_info:
        user = "insert into user(name, mobile) values ('游客%s',%s)" %(args['mobile'][-4:], args['mobile'])
        db.update(user)
        db.commit()
        return jsonify({
            "code": 200,
            "msg": "注册成功"
        })
    sql = "select * from user where mobile=%s" %args['mobile']
    user_info = db.find(sql)

    token = JwtTool().jwt_encode({
        "id": user_info['id'],
        "name": "游客" + args['mobile'][-4:],
        "mobile": args['mobile']
    })

    return jsonify({
        'code': 200,
        'msg': '登录成功',
        "user_id": user_info['id'],
        'token': token
    })


# 三方登录
@user_bp.route('/weibo')
def weibo_login():
    # 微博唯一标识
    clientid = "3674019597"
    # 回调地址
    url = "http://127.0.0.1:8000/user/weiboCallback/"

    reUrl = "https://api.weibo.com/oauth2/authorize?client_id=" + clientid + "&redirect_uri=" + url + "&response_type=code"
    return jsonify({'code': 200, 'url': reUrl})


# 回调接口
@user_bp.route('/weiboCallback/')
def weiboCallback():
    code = request.args.get('code')
    geturl = "https://api.weibo.com/oauth2/access_token"
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post(geturl, data=data)
    print(" --------------------",res)

    # 获取token sf_id
    reponse = res.json()
    print(reponse,"?????????????")
    try:
        token = reponse['access_token']
        sf_id = reponse['uid']
    except Exception as e:
        print(e)
        token = ''
        sf_id = ''

    # 通过 sf_id去三方登录表中查询是否存在
    # user_info = Sflogin.query.filter_by(sf_id=sf_id).first()
    # print("11111",user_info)
    sql = "select * from sflogin where sf_id=%s" %sf_id
    user_info = db.find(sql)
    print("111111",user_info)

    # 如果存在用userid生成token，redirect到vue页面
    if user_info:
        # 生成token
        token = JwtTool().jwt_encode({
            "id": user_info['user_id'],
            'exp': time.time() + 86400  # 现在时间 + 24小时
        })
        print("token______:", token)
        return redirect("http://localhost:8080/is?token=" + token + "&user_id=" + str(user_info['user_id']))
    else:
        return redirect("http://localhost:8080/bindmobile?token=" + token + "&sf_id=" + sf_id)


# 绑定手机号
@user_bp.route('/bindMobile', methods=['POST'])
def bindMobile():
    # 获取参数
    req = reqparse.RequestParser()
    req.add_argument("mobile", required=True)
    req.add_argument("token", required=True)
    req.add_argument("sf_id", required=True)
    args = req.parse_args()

    # 查看用户表中手机号是否存在
    sql = "select * from user where mobile=%s" % args['mobile']
    user_info = db.find(sql)
    print(user_info)
    print(user_info['id'])

    if user_info:
        # 生成token
        token = JwtTool().jwt_encode({
            "id": user_info['id'],
            "name": "游客" + args['mobile'][-4:],
            "mobile": args['mobile']
        })
    else:
        user = "insert into user(name, mobile) values ('游客%s',%s)" % (args['mobile'][-4:], args['mobile'])
        db.update(user)
        db.commit()

        sql = "select * from user where mobile=%s" % args['mobile']
        user_info = db.find(sql)

        # 生成token
        token = JwtTool().jwt_encode({
            "id": user_info['id'],
            "name": "游客" + args['mobile'][-4:],
            "mobile": args['mobile']
        })
    # # 写入三方登录表
    user = "insert into sflogin(token, user_id, sf_id, three_name) values ('%s',%d,'%s','%s')" % (args['token'], user_info['id'], args['sf_id'], 'weibo')
    db.update(user)
    db.commit()

    return jsonify({
        'code': 200,
        'msg': '登录成功',
        "user_id": user_info['id'],
        "token": token
    })


# 查看用户
@user_bp.route('/get_user')
def get_user():
    user_id = request.args.get("user_id")

    sql = "select * from user where id='%s'" %user_id
    user_info = db.find(sql)

    return jsonify({
        "code": 200,
        "msg": "查看用户成功",
        "user_info": user_info,
    })


# 退出登录
# @user_bp.route('/logout')
# def logout():
#     # token = request.headers.get('token')
#     # pkey = "toeknlist"
#     # t = int(time.time())
#     # print(r.zset_add(pkey, t, token))
#     return jsonify({
#         "code": 200,
#         "msg": "退出成功"
#     })

